// 登录注册模态框控制
class AuthModal {
    constructor() {
        // 等待DOM加载完成后再初始化
        setTimeout(() => {
            this.modal = document.getElementById('authModal');
            this.loginForm = document.getElementById('loginForm');
            this.registerForm = document.getElementById('registerForm');
            this.tabs = document.querySelectorAll('.auth-tab');
            this.closeBtn = document.querySelector('.close-btn');
            
            this.initializeEventListeners();
        }, 100);
    }

    initializeEventListeners() {
        // 切换表单
        this.tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const targetForm = tab.dataset.tab;
                this.switchForm(targetForm);
            });
        });

        // 关闭模态框
        this.closeBtn.addEventListener('click', () => this.close());
        this.modal.addEventListener('click', (e) => {
            if (e.target === this.modal) {
                this.close();
            }
        });

        // 表单提交
        this.loginForm.addEventListener('submit', (e) => this.handleLogin(e));
        this.registerForm.addEventListener('submit', (e) => this.handleRegister(e));

        // 社交登录
        document.querySelector('.social-icon.wechat').addEventListener('click', () => this.handleWechatLogin());
        document.querySelector('.social-icon.qq').addEventListener('click', () => this.handleQQLogin());
    }

    open(formType = 'login') {
        this.modal.classList.add('active');
        this.switchForm(formType);
        document.body.style.overflow = 'hidden';
    }

    close() {
        this.modal.classList.remove('active');
        document.body.style.overflow = '';
        this.resetForms();
    }

    switchForm(formType) {
        // 切换标签激活状态
        this.tabs.forEach(tab => {
            tab.classList.toggle('active', tab.dataset.tab === formType);
        });

        // 切换表单显示
        this.loginForm.classList.toggle('active', formType === 'login');
        this.registerForm.classList.toggle('active', formType === 'register');
    }

    resetForms() {
        this.loginForm.reset();
        this.registerForm.reset();
    }

    async handleLogin(e) {
        e.preventDefault();
        const email = document.getElementById('loginEmail').value;
        const password = document.getElementById('loginPassword').value;
        const rememberMe = document.getElementById('rememberMe').checked;

        try {
            // TODO: 实现登录逻辑
            const response = await this.loginUser(email, password, rememberMe);
            if (response.success) {
                this.close();
                // 更新用户状态
                this.updateUserState(response.user);
            } else {
                this.showError(response.message);
            }
        } catch (error) {
            this.showError('登录失败，请稍后重试');
        }
    }

    async handleRegister(e) {
        e.preventDefault();
        const email = document.getElementById('registerEmail').value;
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (password !== confirmPassword) {
            this.showError('两次输入的密码不一致');
            return;
        }

        try {
            // TODO: 实现注册逻辑
            const response = await this.registerUser(email, username, password);
            if (response.success) {
                this.switchForm('login');
                this.showSuccess('注册成功，请登录');
            } else {
                this.showError(response.message);
            }
        } catch (error) {
            this.showError('注册失败，请稍后重试');
        }
    }

    handleWechatLogin() {
        // TODO: 实现微信登录
        console.log('微信登录');
    }

    handleQQLogin() {
        // TODO: 实现QQ登录
        console.log('QQ登录');
    }

    // API 调用方法
    async loginUser(email, password, rememberMe) {
        // TODO: 实现登录 API 调用
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    success: true,
                    user: {
                        id: 1,
                        username: '测试用户',
                        email: email
                    }
                });
            }, 1000);
        });
    }

    async registerUser(email, username, password) {
        // TODO: 实现注册 API 调用
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    success: true,
                    message: '注册成功'
                });
            }, 1000);
        });
    }

    // 辅助方法
    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'auth-message error';
        errorDiv.textContent = message;
        this.modal.querySelector('.auth-container').insertBefore(errorDiv, this.modal.querySelector('.auth-form.active'));
        
        setTimeout(() => {
            errorDiv.remove();
        }, 3000);
    }

    showSuccess(message) {
        const successDiv = document.createElement('div');
        successDiv.className = 'auth-message success';
        successDiv.textContent = message;
        this.modal.querySelector('.auth-container').insertBefore(successDiv, this.modal.querySelector('.auth-form.active'));
        
        setTimeout(() => {
            successDiv.remove();
        }, 3000);
    }

    updateUserState(user) {
        // 更新用户状态
        localStorage.setItem('user', JSON.stringify(user));
        // 更新UI
        document.querySelector('.nav-auth').innerHTML = `
            <button class="auth-btn" onclick="handleLogout()">退出登录</button>
        `;
    }
}

// 创建实例
const authModal = new AuthModal();

// 导出实例
export default authModal; 